
package com.rt.schedulenew.utils.base;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
public class MillisecondClock
{
    private volatile long now;
    
    private MillisecondClock() {
        this.now = System.currentTimeMillis();
        this.scheduleTick();
    }
    
    private void scheduleTick() {
        new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(final Runnable r) {
                final Thread thread = new Thread(r, "current-time-millis");
                thread.setDaemon(true);
                return thread;
            }
        }).scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                MillisecondClock.this.now = System.currentTimeMillis();
            }
        }, 1L, 1L, TimeUnit.MILLISECONDS);
    }
    
    public long now() {
        return this.now;
    }
    
    public static MillisecondClock getInstance() {
        return SingletonHolder.INSTANCE;
    }
    
//    public static void main(final String[] args) {
//        for (int i = 0; i < 1000; ++i) {
//            final long now = getInstance().now();
//            try {
//                Thread.sleep(1000L);
//            }
//            catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//    }
    
    private static class SingletonHolder
    {
        private static final MillisecondClock INSTANCE;
        
        static {
            INSTANCE = new MillisecondClock();
        }
    }
}
